package com.jfire.socket.socketserver.util;

import java.nio.ByteBuffer;

public final class DefaultHeadFactory implements HeadFactory
{
    /**
     * 第一位为0x1b,第二位是command位的取反，第三位是第二位与第四位的异或，第四位数值随机
     */
    @Override
    public void putHeadInBuffer(ByteBuffer buffer, byte command, int length)
    {
        byte one = 0x1b;
        byte two = (byte) ~command;
        byte four = (byte) length;
        byte three = (byte) (two ^ four);
        buffer.put(one).put(two).put(three).put(four);
    }
    
    @Override
    public boolean fitHeadPtotocol(ByteBuffer buffer, int position)
    {
        byte command = buffer.get(position + 5);
        if (buffer.get(position) != (byte) 0x1b)
        {
            return false;
        }
        if (buffer.get(position + 1) != (byte) ~command)
        {
            return false;
        }
        if (buffer.get(position + 2) != (byte) (buffer.get(position + 1) ^ buffer.get(position + 3)))
        {
            return false;
        }
        return true;
    }
}
